package bar.dark.lee.setting.category;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;

public class CategoryMoveActivity extends SuperActivity
{
private DBSQLite sql;
	
	private Button insertButton;
	private EditText categoryEditText;
	private ListView listView;
	
	private ArrayList<CategoryData> list;
	
	private View resultView;
	
	private int maxCount;
	
	
	public static final String CATEGORY_MONEY_SERVICE = "현금서비스";
	public static final String CATEGORY_MONEY_INOUT = "현금인출";
	public static final String CATEGORY_MONEY_OUTIN = "현금입금";
	public static final String CATEGORY_SUSUMONEY = "수수료";
	public static final String CATEGORY_FAN_OUT_MONEY = "빌려준금액";
	public static final String CATEGORY_FAN_IN_MONEY = "빌린금액";
	public static final String CATEGORY_FAN_OUT_CHECK = "받은금액";
	public static final String CATEGORY_FAN_IN_CHECK = "갚은금액";
	public static final String CATEGORY_POST_OUT = "카드대금결제";
	
	private String[] fixCategory = new String[]{
			BDConstents.CATEGORY_SUSUMONEY,
			BDConstents.CATEGORY_FAN_OUT_MONEY,
			BDConstents.CATEGORY_FAN_IN_MONEY,
			BDConstents.CATEGORY_FAN_OUT_CHECK,
			BDConstents.CATEGORY_FAN_IN_CHECK,
			BDConstents.CATEGORY_POST_OUT,
			BDConstents.CATEGORY_USE_CARD,
			BDConstents.CATEGORY_IN_CARD,
			BDConstents.CATEGORY_OUT_CARD,
			BDConstents.CATEGORY_OUT_BANK,
			BDConstents.CATEGORY_IN_BANK
		};
	
	public static final String TITLE_VISIBLE = "title_visible";
	
	private boolean flagTitle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.setting_category);
		
		Intent intent = getIntent();
		flagTitle = intent.getBooleanExtra(TITLE_VISIBLE, false);

		if (flagTitle)
		{
			setTitle("이동 카테고리 추가");
			setGoneTipButton();
		}
		else
		{
			setGoneTitle();
		}
		
		setFindView();
		initClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}

	private void setFindView()
	{
		categoryEditText = (EditText) findViewById(R.id.settingCategoryEditText);
		listView = (ListView) findViewById(R.id.settingCategoryList);
		insertButton = (Button) findViewById(R.id.settingCategoryInsertButton);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		resultView = li.inflate(R.layout.view_no_result, null);
	}
	
	private void initDataSetting()
	{
		sql.selectMapTile(this, "SELECT * FROM category_move_list ORDER BY count DESC;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				list = new ArrayList<CategoryData>();
				
				int id = c.getColumnIndex("id");
				int kind = c.getColumnIndex("kind");
				int count = c.getColumnIndex("count");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					CategoryData data = new CategoryData();
					data.setId(c.getInt(id) + "");
					data.setKind(c.getString(kind));
					data.setCount(c.getInt(count) + "");
					list.add(data);
					
					if (i == 0)
					{
						maxCount = c.getInt(count);
					}
					
					c.moveToNext();
				}
			}
		});
	}
	
	private OnItemClickListener itemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int postion,
				long arg3)
		{
			CategoryData data = list.get(postion);
			Intent intent = new Intent(CategoryMoveActivity.this, CategoryEditActivity.class);
			intent.putExtra(CategoryTabActivity.CATEGORY_DATA, data);
			intent.putExtra(CategoryTabActivity.CATEGORY_FLAG, CategoryTabActivity.MOVE);
			startActivity(intent);
		}
	};
	
	private void initClickListener()
	{
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCheckData();
			}
		});
	}
	
	private void setCheckData()
	{
		if (categoryEditText.getText().toString().length() < 1)
		{
			BDUtil.showDialog(this, "카테고리에러", "카테고리를 입력해주세요.");
			return;
		}
		
		if (BDUtil.getOverlapCheck(sql, this, "SELECT id FROM category_out_list WHERE kind = '"
				+ BDUtil.getApostrophe(categoryEditText.getText().toString()) + "';"))
		{
			BDUtil.showDialog(this, "카테고리에러", "지출에 이미 같은 이름의 카테고리가 있습니다.");
			categoryEditText.setText("");
			return;
		}
		
		if (BDUtil.getOverlapCheck(sql, this, "SELECT id FROM category_in_list WHERE kind = '"
				+ BDUtil.getApostrophe(categoryEditText.getText().toString()) + "';"))
		{
			BDUtil.showDialog(this, "카테고리에러", "수입에 이미 같은 이름의 카테고리가 있습니다.");
			categoryEditText.setText("");
			return;
		}
		
		if (BDUtil.getOverlapCheck(sql, this, "SELECT id FROM category_move_list WHERE kind = '"
				+ BDUtil.getApostrophe(categoryEditText.getText().toString()) + "';"))
		{
			BDUtil.showDialog(this, "카테고리에러", "이동에 이미 같은 이름의 카테고리가 있습니다.");
			categoryEditText.setText("");
			return;
		}
		
		for (int i=0; i<fixCategory.length; i++) {
			if (categoryEditText.getText().toString().equals(fixCategory[i])) {
				BDUtil.showDialog(this, "카테고리에러", "'"+fixCategory[i]+"'는 이미 고정된 카테고리로 사용중인 단어입니다.");
				categoryEditText.setText("");
				return;
			}
		}
		
		if (categoryEditText.getText().toString().equals(BDConstents.CATEGORY_SUSUMONEY))
		{
			BDUtil.showDialog(this, "카테고리에러", "'수수료'는 카테고리로 사용할수 없는 단어입니다.");
			categoryEditText.setText("");
			return;
		}
		
		new ShowDialog().execute(BDUtil.asyncFlag, 2);
	}
	
	private void setInsertCategory()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("kind", categoryEditText.getText().toString());
		map.put("count", "" + maxCount);
		sql.insert(this, map, "category_move_list");
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(CategoryMoveActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					initDataSetting();
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setInsertCategory();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						e.printStackTrace();
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} 
			else
			{
				return arg0[0];
			}
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (list.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setHeaderDividersEnabled(false);
				}
				else
				{
					listView.setOnItemClickListener(itemClickListener);
				}
				
				CategoryAdapter adapter = new CategoryAdapter(CategoryMoveActivity.this, R.layout.list_item_category, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.showDialog(CategoryMoveActivity.this, "알림", "카테고리가 추가 되었습니다.");
				
				categoryEditText.setText("");
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
				
				if (flagTitle)
				{
					Intent intent = new Intent();
					setResult(RadioDialogActivity.REFRESH_CATEGORY, intent);
				}
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
